package com.ruoyi.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc   使用token验证用户是否登录
 * @author
 **/
public class JwtTokenUtils {

    //设置过期时间
    private static final long EXPIRE_DATE = 20 * 60 * 1000L;
    //token秘钥
    private static final String TOKEN_SECRET = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=";

    public static String token (Long custId,String password){

        String token = "";
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis()+EXPIRE_DATE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String,Object> header = new HashMap<>();
            header.put("typ","JWT");
            header.put("alg","HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("custId",custId)
                    .withClaim("password",password).withExpiresAt(date)
                    .sign(algorithm);
        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }
        return token;
    }

    /**
     * token校验是否正确
     * @param token
     * @return
     */

    public static boolean verify(String token){
        try{
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);

            JWTVerifier verifier = JWT.require(algorithm).build();

            DecodedJWT decodedJWT = verifier.verify(token);

            return true;

        }catch (Exception e){
            System.out.println("Token过时,需要重新登录");
        }
        return false;
    }

    /**
     * 获取token中信息 userName
     * @param token
     * @return
     */

    public static Long getCustId(String token){
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("custId").asLong();

        }catch (JWTDecodeException e){
            e.printStackTrace();
        }
        return null;
    }


}